package edu.tms.crud;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import edu.tms.crud.PropertyReader;

public class ConnectionPool {
	 private static ComboPooledDataSource connectionPool;
	 
	 static{
		 try {
			connectionPool = new ComboPooledDataSource();
			
			connectionPool.setDriverClass(PropertyReader.get("driver"));
			
			connectionPool.setJdbcUrl(PropertyReader.get("url"));//设置连接数据库的URL  
			
			connectionPool.setUser(PropertyReader.get("user"));//设置连接数据库的用户名  
			
			connectionPool.setPassword(PropertyReader.get("password"));//设置连接数据库的密码  
	              
			connectionPool.setMaxPoolSize(Integer.parseInt(PropertyReader.get("maxPoolSize")));//设置连接池的最大连接数  
	              
			connectionPool.setMinPoolSize(Integer.parseInt(PropertyReader.get("minPoolSize")));//设置连接池的最小连接数  
	              
			connectionPool.setInitialPoolSize(Integer.parseInt(PropertyReader.get("initPoolSize")));//设置连接池的初始连接数  
	              
			connectionPool.setMaxStatements(Integer.parseInt(PropertyReader.get("maxStatements")));//设置连接池的缓存Statement的最大数 
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	 }
	 
	 //获取与指定数据库的连接  
	 public static DataSource getInstance(){  
		 return connectionPool;  
	 }   
	  
	//从连接池返回一个连接  
	public static Connection getConnection(){  
	    Connection conn = null;  
	    try {  
	        conn = connectionPool.getConnection();  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    }  
	    return conn;  
	}
	
	
	//释放资源  
    public static void realeaseResource(ResultSet rs,PreparedStatement ps,Connection conn){  
        if(null != rs){  
            try {  
                rs.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
          
        if(null != ps){  
            try {  
                ps.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
  
        try {  
            conn.close();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }  
	
}
